let workers = {};
function register(worker, dir) {
    workers[worker] = {
        worker: new Worker(`${dir}_worker.js`),
        listeners: []
    };
    workers[worker].worker.onmessage = function(e) {
        workers[worker].listeners.forEach(item => {
            if (typeof item === 'function') {
                const { data } = e;
                item(workers[worker].worker, data);
            }
        })
    }
}

function addWorkerListener(worker, listener) {
    if (workers[worker]) {
        let index = workers[worker].listeners.findIndex((item) => item.toString() === listener.toString());
        if (index === -1) {
            workers[worker].listeners.push(listener);
        }
    }
}

function removeWorkerListener(worker, listener) {
    if (workers[worker]) {
        let index = workers[worker].listeners.findIndex((item) => item.toString() === listener.toString());
        if (index >= 0) {
            worker[worker].listeners.splice(index, 1);
        }

    }
}

function send(worker, message) {
    if (workers[worker]) {
        workers[worker].worker.postMessage(message);
    }
}

export function injectWorker(XUE) {
    XUE.worker = {
        register,
        addWorkerListener,
        removeWorkerListener,
        send
    };
}
